package com.kma.summer2012.client.presenters.mainPage.widgets;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.DialogBoxFactory;
import com.kma.summer2012.client.ExceptionHandling.ExceptionProcessor;
import com.kma.summer2012.client.constants.ConstantsPresenter;
import com.kma.summer2012.client.events.UpdateCellTableEvent;
import com.kma.summer2012.client.events.engineer.CloseRequestEvent;
import com.kma.summer2012.client.events.engineer.EngineerShowRequestEvent;
import com.kma.summer2012.client.events.manager.EditPageEventManager;
import com.kma.summer2012.client.events.operator.EditPageEvent;
import com.kma.summer2012.client.events.reject.RejectRequestEvent;
import com.kma.summer2012.client.events.request.RequestsSelectedEvent;
import com.kma.summer2012.client.presenters.header.HeaderPresenter;
import com.kma.summer2012.client.services.request.CrumbsRequestService;
import com.kma.summer2012.client.view.PopUpPreloader;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import com.kma.summer2012.shared.model.UICrumbsUser;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: EUGENE
 * Date: 2/14/13
 * Time: 2:43 AM
 * To change this template use File | Settings | File Templates.
 */
public class DownBarPresenter extends PositionHolder implements IDownBarPresenter {
    private static ConstantsPresenter constants;
    private Display display;
    private CrumbsEventBus eventBus = CrumbsEventBus.getInstance();

    private List<UICrumbsRequest> currentRequests = new ArrayList<UICrumbsRequest>();
    private Integer tableID;

    public DownBarPresenter(Display display) {
        this.display = display;
        showButtons();
        bind();
    }

    private void bind() {
        eventBus.addHandler(RequestsSelectedEvent.getType(), new RequestsSelectedEvent.RequestSelectedEventHandler() {
            @Override
            public void onRequestsSelected(RequestsSelectedEvent event) {
                if (tableID.equals(event.tableID))
                    doRequestsSelected(event.requests);
            }
        });

        display.getEditBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doEdit(DownBarPresenter.this.currentRequests);
            }
        });
        display.getCloseBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doClose();
            }
        });
        display.getDeleteBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                List<HasClickHandlers> list = new ArrayList<HasClickHandlers>();
                list.add(new Button("Delete", new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent clickEvent) {
                        doDelete();//To change body of implemented methods use File | Settings | File Templates.
                    }
                }));
                DialogBoxFactory.createMessageBox("Do you really want to delete this tool?", "O'RLY?", list).show();
            }
        });
        display.getRejectBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doReject();
            }
        });
        display.getSendForProcessingBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doSendForProcessing();
            }
        });
    }

    private void doEdit(List<UICrumbsRequest> set) {
        if (set.size() > 1) {
            return;
        } else {
            if (set.size() == 1) {
                UICrumbsRequest request = (UICrumbsRequest) (set.toArray())[0];
                GwtEvent event = null;
                if (position.equals(UICrumbsUser.MANAGER_POSITION)) {

                    event = (new EditPageEventManager(request));
                }
                if (position.equals(UICrumbsUser.OPERATOR_POSITION)) {
                    event = (new EditPageEvent(request));
                }
                if (position.equals(UICrumbsUser.ENGINEER_POSITION)) {
                    event = (new EngineerShowRequestEvent(request));
                }
                if (event != null)
                    eventBus.fireEvent(event);
            }
        }
    }

    private void doRequestsSelected(List<UICrumbsRequest> requests) {
        currentRequests = requests;
        if (currentRequests == null || currentRequests.size() == 0) {
            this.display.enableCloseBtn(false);
            this.display.enableDeleteBtn(false);
            this.display.enableRejectBtn(false);
            this.display.enableSendForProcessingBtn(false);
        } else {
            //reject button
            Boolean validateRejected = true;
            for (UICrumbsRequest request : currentRequests) {
                if (request.getStateId() == 4 || request.getStateId() == 5 || (request.getStateId() == 2 && request.getEngineer() == null)) {
                    validateRejected = false;
                    break;
                }
            }
            if (validateRejected) {
                this.display.enableSendForProcessingBtn(true);
            } else {
                this.display.enableSendForProcessingBtn(false);
            }

            this.display.enableRejectBtn(currentRequests.size() == 1);
            this.display.enableCloseBtn(currentRequests.size() == 1);
            this.display.enableEditBtn(currentRequests.size() == 1);
            this.display.enableEditBtn(currentRequests.size() == 1);

            Boolean validateNew = true;
            for (UICrumbsRequest request : currentRequests) {
                if (!(request.getStateId() == 1)) {
                    validateNew = false;
                    break;
                }
            }

            this.display.enableDeleteBtn(validateNew);
        }
    }

    private void showButtons() {
        String position = HeaderPresenter.getUser().getPosition();
        if (position.equals(UICrumbsUser.OPERATOR_POSITION)) {
            this.display.showEditBtn(true);
            this.display.showDeleteBtn(true);
            this.display.showSendForProcessingBtn(true);
            this.display.showCloseBtn(false);
            this.display.showRejectBtn(false);
            this.display.setEditButtonText("Edit");
        } else if (position.equals(UICrumbsUser.MANAGER_POSITION)) {
            this.display.showEditBtn(true);
            this.display.showEditBtn(true);
            this.display.showDeleteBtn(false);
            this.display.showSendForProcessingBtn(true);
            this.display.showCloseBtn(false);
            this.display.showRejectBtn(true);
            this.display.setEditButtonText("Edit");
        } else if (position.equals(UICrumbsUser.ENGINEER_POSITION)) {
            this.display.showEditBtn(true);
            this.display.showDeleteBtn(false);
            this.display.showSendForProcessingBtn(false);
            this.display.showCloseBtn(true);
            this.display.showRejectBtn(true);
            this.display.setEditButtonText("Show");
        }
        this.display.enableEditBtn(false);
        this.display.enableCloseBtn(false);
        this.display.enableDeleteBtn(false);
        this.display.enableRejectBtn(false);
        this.display.enableSendForProcessingBtn(false);
    }

    private void doSendForProcessing() {
        // this.eventBus.fireEvent(new SendForProcessingRequestEvent(this.currentRequests));
        PopUpPreloader.show();
        CrumbsRequestService.App.getInstance().sendAllForProcessing(HeaderPresenter.getUser().getUserId(), this.currentRequests, new AsyncCallback<Boolean>() {
            @Override
            public void onFailure(Throwable throwable) {
                PopUpPreloader.hide();
                ExceptionProcessor.getInstance().processServiceFailure(throwable);

            }

            @Override
            public void onSuccess(Boolean aBoolean) {
                PopUpPreloader.hide();
                if (aBoolean) {
                    Window.alert("Successfully sent");
                    DownBarPresenter.this.eventBus.fireEvent(new UpdateCellTableEvent(tableID));
                } else {
                    Window.alert("Cannot send");
                }
            }
        });


    }

    private void doReject() {
        this.eventBus.fireEvent(new RejectRequestEvent(this.currentRequests.get(0)));
    }

    private void doClose() {
        this.eventBus.fireEvent(new CloseRequestEvent(this.currentRequests.get(0)));
    }

    private void doDelete() {
        /*List<UICrumbsRequest> uiCrumbsRequestList=new ArrayList<UICrumbsRequest>();
        for (int i = 0; i < this.currentRequests.size(); i++)
            uiCrumbsRequestList.add(this.currentRequests.get(i));
         */
        PopUpPreloader.show();
        List<Integer> requestIdList = new ArrayList<Integer>();
        for (int i = 0; i < this.currentRequests.size(); i++)
            requestIdList.add(this.currentRequests.get(i).getId());

        CrumbsRequestService.App.getInstance().deleteRequests(requestIdList, new AsyncCallback<Boolean>() {
            @Override
            public void onFailure(Throwable throwable) {
                PopUpPreloader.hide();
                ExceptionProcessor.getInstance().processServiceFailure(throwable);
            }

            @Override
            public void onSuccess(Boolean boo) {
                if (boo) {
                    PopUpPreloader.hide();
                    Window.alert("Request was deleted");
                    DownBarPresenter.this.eventBus.fireEvent(new UpdateCellTableEvent(tableID));
                } else {
                    PopUpPreloader.hide();
                    Window.alert("Request wasn't deleted");
                }
            }
        });


    }

    @Override
    public void setTableID(Integer id) {
        this.tableID = id;
    }
}
